// SEVER SIDE

/* TABLE OF CONTENTS
[L-23] InitialSpawn ~ The Initial Spawn Script
[L-65] PlayerDeath ~ Become Spectator upon death, ALSO announce who killed you, ALSO spawn last weapon as entity
[L-130] PlayerSpawn ~ Checks whether player wants new team or stays on same team.
[L-154] SwitchTDMTeamIndex ~ Player requested new team, and will be checked if alive or dead
[L-172] SwitchTDMTeam ~ Will give players team values upon request of server
[L-207] BlockSuicide ~ Does not allowed players to suicide for any reason
[L-217] ArmorSCript ~ Creates the armor script so when the variable is changed, it changes too
[L-229] ArmorButton ~ Changes the variable upon request of player or server
[L-260] CustomTeamSpawn ~ Will spawn each player on the specific team spawn, if exists

*/

// Initial Server Start Vars
game.ConsoleCommand("sv_voiceenable 1\n")
game.ConsoleCommand("sv_alltalk 3\n")



// Initial Spawn Set Commands
function PlayerInitialSpawnTDM(ply)
	function PlaceOnTeam()
		local GetPlayers = player.GetAll()
	for k,v in pairs(GetPlayers) do
		if v:IsValid() then
			v:SetPData("TDM_Total_Score_Ok", 0)
			v:SetPData("MyTimerLimiter", 0)
			umsg.Start("PlaceScoreForMenu")
				umsg.Short(k)
				umsg.Short(file.Read("TDM/GoalLimit/GoalLimit.txt"))
			umsg.End()
			
			umsg.Start("TimeLimitUnOfficialMenu")
				umsg.String(file.Read("TDM/Timer/TimerLimit.txt","DATA") / 60)
				umsg.String(k)
			umsg.End()
		end
	end
		ply:SetPData("SetOldTeam", 0)
		ply:SetPData("SetNewTeam", 1001)
		ply:SetPData("KSPoints", 0)
		ply:SetPData("KSPointsTime", 0)
		ply:SetPData("TDM_Total_Score_Ok", 0)
		ply:SetPData("MyTimerLimiter", 0)
		local GetAllTeamID={}
		for k,v in pairs(AddTeams) do
		GetAllTeamID[k..":"]=k
		end
	local BreakTeamID = string.Explode(":",table.Random(GetAllTeamID))

--	timer.Simple( 0.5, function()
		if ply:IsValid() then
			ply:AllowFlashlight( true )
				for k,v in pairs(team.GetAllTeams()) do
					if k != 0 and k < 1000 then
					CheckForMore = team.NumPlayers(k)
					CheckRanTeam = tonumber(BreakTeamID[1])
					Conclusion = team.NumPlayers(CheckRanTeam)
					end
				end
			if CheckForMore >= Conclusion then
			// Switch Team, selected team is lower or equal to All Other Teams
			timer.Simple( 0.5, function()
				if ply:IsValid() then
					ply:SetPData("SetNewTeam", tonumber(CheckRanTeam))
					SwitchTDMTeam(ply, cmds, CheckRanTeam)
					ply:Spawn()
					umsg.Start( "TDM_Welcome_To_Server", ply)
					umsg.String(ply:Nick())
					umsg.Short(ply:Team())
					umsg.End()
				end
			end)
			elseif CheckForMore <= Conclusion then
			// Switch Team is higher than All Other Teams
				PlaceOnTeam()
			else
				MsgN("[TDM] You shouldn't be able to see this.")
			end
		end
--	end)
	end
PlaceOnTeam()
end
hook.Add( "PlayerInitialSpawn", "PlayerInitialSpawnTDM", PlayerInitialSpawnTDM )
	
	
	
// Player Death to Spectator
function PlayerDeathTDM( ply, wep, killer )
if killer == nil || !killer:IsValid() then return end
function PlayerDeathTDMCon( ply, wep, killer )
timer.Simple( 5, function()
	if ply:IsValid() then 
	if ply:Alive() == true then return end
		ply:UnSpectate()
		ply:Spawn()
/*
	if ply:IsBot() then
		ply:UnSpectate()
		SwitchTDMTeam(ply, cmds, args)
	else
	local CheckIfWantsNewTeam = tonumber(ply:GetPData("SetNewTeam"))
		if CheckIfWantsNewTeam != args then
		ply:UnSpectate()
		SwitchTDMTeam(ply, cmds, CheckIfWantsNewTeam)
		else
		ply:UnSpectate()
		SwitchTDMTeam(ply, cmds, args)
		end
	end
*/
	end
end)
end

if killer == ply then 
	umsg.Start( "TDM_Killed_Self", ply)
	umsg.End()
PlayerDeathTDMCon( ply, wep, killer )
elseif killer:Team() == ply:Team() then
	umsg.Start( "TDM_Who_Team_Killed_Me", ply)
	umsg.String(killer:Nick())
	umsg.Short(killer:Team())
	umsg.End()
	umsg.Start( "TDM_Who_Did_I_Team_Kill", killer)
	umsg.String(ply:Nick())
	umsg.Short(ply:Team())
	umsg.End()
ply:Spectate( OBS_MODE_IN_EYE )
ply:SpectateEntity( killer )
PlayerDeathTDMCon( ply, wep, killer )
else
local ent = ents.Create(ply:GetPData("GetLastWeapon"))
ent:SetPos(ply:GetPos())
ent:Spawn()
	umsg.Start( "TDM_Who_Killed_Me", ply)
	umsg.String(killer:Nick())
	umsg.Short(killer:Team())
	umsg.End()
	umsg.Start( "TDM_Who_Did_I_Kill", killer)
	umsg.String(ply:Nick())
	umsg.Short(ply:Team())
	umsg.End()
ply:Spectate( OBS_MODE_IN_EYE )
ply:SpectateEntity( killer )
PlayerDeathTDMCon( ply, wep, killer )
end
end
hook.Add( "PlayerDeath", "PlayerDeathTDM", PlayerDeathTDM )



// Player Respawns and checks if new team is needed
function PlayerSpawnTDM( ply )
-- timer.Simple( 1, function()
if ply:IsValid() then 
local args = tonumber(ply:Team())
if args == nil || args == 0 || args > 1000 then return end -- Due to some sort of glitch, this has to be here.
	ply:UnSpectate()
	if ply:IsBot() then
	SwitchTDMTeam(ply, cmds, args)
	else
	local CheckIfWantsNewTeam = tonumber(ply:GetPData("SetNewTeam"))
		if CheckIfWantsNewTeam != args then
		SwitchTDMTeam(ply, cmds, CheckIfWantsNewTeam)
		else
		SwitchTDMTeam(ply, cmds, args)
		end
	end
end
-- end)
end
hook.Add( "PlayerSpawn", "PlayerSpawnTDM", PlayerSpawnTDM )

	
	
// Check if player is alive when requesting change
function SwitchTDMTeamIndex(ply, cmds, args)
if !ply:Alive() then
ply:Spawn()
SwitchTDMTeam(ply, cmds, tonumber(args[1]))
ply:SetPData("SetOldTeam", tonumber(ply:Team()))
ply:SetPData("SetNewTeam", tonumber(args[1]))
else
ply:SetPData("SetOldTeam", tonumber(ply:Team()))
ply:SetPData("SetNewTeam", tonumber(args[1]))
umsg.Start( "TDM_Alive_Cant_Switch", plu)
umsg.String(team.GetName(tonumber(args[1])))
umsg.Short(tonumber(args[1]))
umsg.End()
end
end
concommand.Add( "SwitchTDMTeamIndex", SwitchTDMTeamIndex )



// Switch Team Function
function SwitchTDMTeam(ply, cmds, args)
if args == nil || args == 0 || args > 1000 then return end -- Due to some sort of glitch, this has to be here.
if !ply:IsValid() then return end
ply:StripWeapons()
ply:StripAmmo()
ply:SetTeam(tonumber(args))

	for k,v in pairs(AddTeams) do
	if v.name == team.GetName(tonumber(args)) then
		// Gives Random Models From Their Team
				local TeamModel = table.Random(v.model)
				ply:SetModel(TeamModel)
		// Gives Weapon
			for k,v in pairs(v.Weapons) do
				ply:Give (v)
			end
		// Gives Ammo for Weapons
			for k,v in pairs(v.Ammo) do
				local AmmoNames = string.Explode("*",v)
				ply:SetAmmo (AmmoNames[2], AmmoNames[1])
			end
		// Gives Them Armor if Armor Script is On
			if tonumber(file.Read("TDM/Armor/Armor.txt","DATA")) == 1 then
				ply:SetArmor(100)
			else
				ply:SetArmor(0)
			end
	end
	end
end


-- Bullshit that's not needed to load first is on the bottom of this line

// Player can not use kill in console to quick team change.
function BlockSuicideTDM(ply)
umsg.Start( "TDM_Can_Kill_Self", ply)
umsg.End()
	return false
end
hook.Add( "CanPlayerSuicide", "BlockSuicideTDM", BlockSuicideTDM )



// Creates the armor script
local DefaultArmor  = "1"
if (not file.IsDir("TDM/Armor","DATA")) then
    file.CreateDir("TDM/Armor")
end
if not(file.Exists("TDM/Armor/Armor.txt","DATA")) then
	file.Write("TDM/Armor/Armor.txt", DefaultArmor)
	print("[TDM] Wrote file : TDM/Armor/Armor.txt")
end



// The Armor Button
function TDMArmorButton( ply, cmd, args )
if ply:IsSuperAdmin() then
if (not file.IsDir("TDM/Armor","DATA")) then
    file.CreateDir("TDM/Armor")
end
if not(file.Exists("TDM/Armor/Armor.txt","DATA")) then
	file.Write("TDM/Armor/Armor.txt", tonumber(args[1]))
	print("[TDM] Wrote file : TDM/Armor/Armor.txt")
end
	file.Write("TDM/Armor/Armor.txt", tonumber(args[1]))
if tonumber(args[1]) == 1 then
ArmorChk = "on"
else
ArmorChk = "off"
end
umsg.Start( "TDM_Changed_Armor" )
umsg.String(ply:Nick())
umsg.Short(ply:Team())
umsg.String(ArmorChk)
umsg.End() 
file.Append( "TDM/Logs/"..os.date("%m-%d-%y")..".txt", os.date("%I:%M:%S").." | "..ply:Nick().." has turned armor "..ArmorChk.." \n" )
else
umsg.Start( "TDM_Not_Admin", ply )
umsg.End()
end
end
concommand.Add( "TDMArmorButton", TDMArmorButton )



// Custom Spawns for Teams
function GM:PlayerSelectSpawn( ply )
	local Team = ply:Team()
	points = ents.FindByClass("team" .. Team)
	if #points == 0 then
	points = ents.FindByClass("info_player_start")
	end
	local OldTeam = tonumber(ply:GetPData("SetOldTeam"))
	local NewTeam = tonumber(ply:GetPData("SetNewTeam"))
	
if ply:IsValid() then
	if OldTeam != NewTeam then
--			MsgN(OldTeam)
--			MsgN(NewTeam)
			ply:SetPData("SetOldTeam", NewTeam)
			ply:SetPData("SetNewTeam", NewTeam)
		timer.Simple( 0.1, function()
			ply:Spawn()
		end)
	end
end
	return points[math.random(#points)]
end